import sqlalchemy as db
from typing import Any, List
from pydantic import BaseModel
from fastapi import APIRouter
import datetime
from core import setting, dbSession
import uuid
import smtplib
from email.mime.text import MIMEText
import asyncio
import email

from ..models import Account

router = APIRouter(
    prefix="/register",
    tags=["register"]
)

class RegisterInfo(BaseModel):
    username:str
    password:str
    email:str

session = dbSession['sqlite']

@router.get("/sendVerifyEmail")
async def sendVerifyEmail(email:str):
    query = session.query(Account).filter(email==Account.email)
    result:Account = query.first()
    if(result==None):
        return {"status":False,"message":"该邮箱未被注册"}
    else:
        activationCode:str = result.activationCode
        body = f"<h1>验证邮件</h1>\n您好，请点击连接完成邮箱验证<a href=https://{setting.host}:{setting.port}/accountApi/verifyAccount/{activationCode}>激活连接</a>"
        msg = MIMEText(body)
        msg['From'] = setting.email
        msg['To'] = email
        msg['Subject'] = 'Test email'

        smtp_obj = smtplib.SMTP('smtp.gmail.com', 587)
        smtp_obj.starttls()
        # Replace the placeholders with the actual credential values
        smtp_obj.login('sender_username', 'sender_password')
        smtp_obj.sendmail(msg['From'], msg['To'], msg.as_string())
        smtp_obj.quit()
        print("Email sent successfully!")
        return {"status":True,"message":"发送验证邮件成功"}
@router.post("/addAccount")
async def addAccount(data:RegisterInfo):
    status = False
    message = ""
    response = {"status":status,"message":message}
    account = Account(**data.__dict__)  
    query = session.query(Account).filter(data.username==Account.username)
    if(query.count()):
        response['status'] = False
        response['message'] = "注册失败，该用户名已注册"
        return response 
    if(session.query(Account).filter(data.email==Account.email).count()):
        response['status'] = False
        response['message'] = "注册失败，该邮箱已注册"
        return response 
    id = session.query(db.func.max(Account.id)).first()[0]
    if id==None:
        id= 0
    else:
        id=id+1
    account.id = id
    account.group = "用户"
    account.buildDate = int(datetime.datetime.now().timestamp()*1000)
    account.verified = False
    account.activationCode = str(uuid.uuid4())
    response["status"] = True 
    response["message"] = "注册成功，请登录邮箱验证"
    session.add(account)
    session.commit()
    return response

@router.get("/verifyAccount/{activationCode}")
async def verifyAccount(activationCode:str):
    query = session.query(Account).filter(Account.activationCode==activationCode)
    if(query.count()):
        account:Account = query.first()
        account.verified = True
        session.commit()
    return {"status":True}